#include "stdafx.h"
#include "ProgTimer.h"
#include "MemTrack.h"

namespace bs
{
	const int DEFAULT_WIDTH = 100;
	const int DEFAULT_HEIGHT = 20;
	const COLORREF DEFAULT_COLOR = RGB(0, 255, 0);

	ProgTimer::ProgTimer()
		: x(0), y(0), w(DEFAULT_WIDTH), h(DEFAULT_HEIGHT), counter(0), target(0), running(false)
	{
		this->hbr = ::CreateSolidBrush(DEFAULT_COLOR);
	}

	ProgTimer::~ProgTimer()
	{
		::DeleteObject(this->hbr);
	}

	bool ProgTimer::SetTime( int duration, int _id /*= 0*/ )
{
		if(this->running)
			return false;

		this->target = duration;
		this->counter = this->target;
		this->id = _id;

		return true;
	}

	void ProgTimer::SetColor( COLORREF color )
	{
		::DeleteObject(this->hbr);

		this->hbr = ::CreateSolidBrush(DEFAULT_COLOR);
	}

	void ProgTimer::Start()
	{
		if(this->target > 0)
		{
			this->counter = 0;
			this->running = true;
		}
	}

	void ProgTimer::Update( int elapse )
	{
		if(!this->running)
			return;

		this->counter += elapse;
		if(this->counter >= this->target)
		{
			this->counter = this->target;
			this->running = false;

			for(std::set<IProgListener*>::iterator itr=this->listeners.begin();
				itr!=this->listeners.end(); ++itr)
			{
				(*itr)->OnTimeUp(this->id);
			}
		}
	}

	void ProgTimer::Draw( HDC dc )
	{
		RECT rt;
		rt.left = this->x;
		rt.top = this->y;
		rt.bottom = rt.top + this->h;

		if(!this->running)
		{
			rt.right = rt.left + this->w;
		}
		else
		{
			rt.right = rt.left + this->w * this->counter / this->target;
		}

		::FillRect(dc, &rt, this->hbr);
	}

	void ProgTimer::Stop()
	{
		this->running = false;
	}
}
